const API = 'https://wx.leeapp.dev/wechat';
const cacheKey = 'wechat_token';

interface IAccessToken {
  access_token: string;
  expires_in: number;
}

export const getToken = async (env: Env): Promise<IAccessToken> => {
  const cache = await env.KV.get<IAccessToken>(cacheKey, 'json');
  if (cache) {
    if (cache.expires_in >= Date.now()) {
      return cache;
    }
  }
  try {
    const resp = await fetch(
      `${API}/access_token`
    ).then(res => res.json() as any as IAccessToken);
    console.log('access_token:', resp);
    if (resp['access_token']) {
      env.KV.put(
        cacheKey,
        JSON.stringify({
          access_token: resp['access_token'],
          expires_in: Date.now() + resp.expires_in,
        })
      );
    }
    return resp;
  } catch (err: any) {
		console.log('access_token error:', err);
    return err;
  }
};

// 新建临时图片
export const addImage = async (env: Env, media: File) => {
  const { access_token = '' } = await getToken(env);
  const form = new FormData();
  form.append('media', media);
  try {
    const resp = await fetch(`${API}/media/upload?access_token=${access_token}&type=image`, {
      method: 'POST',
      body: form,
    }).then(res => res.json() as any);
    console.log(resp);
    return resp;
  } catch (err) {
    console.log(err);
    return err;
  }
};

// 新建图文消息草稿
interface IDraft {
  title: string;
  author?: string;
  digest?: string;
  content: string;
  content_source_url?: string;
  thumb_media_id?: string;
  need_open_comment?: 0 | 1;
}
export const addDraft = async (env: Env, body: IDraft) => {
  const { access_token = '' } = await getToken(env);
  try {
    const resp = await fetch(`${API}/draft/add?access_token=${access_token}`, {
      method: 'POST',
      body: JSON.stringify(body),
    }).then(res => res.json() as any);
    console.log('draft: ', resp);
    return resp;
  } catch (err) {
    console.log('draft error:', err);
    return err;
  }
};
